#include "clienttransfer.h"
#include "timestamp.h"

ClientTransfer::ClientTransfer()
{
    this->m_sock.bind(DEFAULT_CLIENT_PORT);
    this->m_request.resize(sizeof(normal_request_t));
    QObject::connect(&this->m_sock, SIGNAL(readyRead()), this, SLOT(recvData()));
    QObject::connect(&this->m_timer, SIGNAL(timeout()), this, SLOT(timerRequest()));
    this->m_timer.stop();
}


void ClientTransfer::recvData(){
    QByteArray datagram;
    QHostAddress sender;
    quint16 senderPort;
    datagram.resize(this->m_sock.pendingDatagramSize());
    this->m_sock.readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
    processDatagram(datagram);
}
void ClientTransfer::timerRequest(){
    if(this->m_req_mutex.tryLock()){



        this->m_req_mutex.unlock();
    }
}

void ClientTransfer::sendRequest(){
    normal_request* req = (normal_request*) this->m_request.data();
    requestInfo(req)->magic = REQUEST_MAGIC;
    requestInfo(req)->timestamp = TimeStamp::now()->toInt();

    this->m_sock.writeDatagram(this->m_request, this->m_server_addr, this->m_server_port);
}

void ClientTransfer::processDatagram(QByteArray datagram){
    if(datagram.size() == sizeof(response_head_t)){
        emit gotResponse(datagram);
    }else if(datagram.size() == sizeof(response_data_t)){
        emit gotImageData(datagram);
    }
}

void ClientTransfer::imgRequest(int timestamp, int seq, int width, int height, int once_count){
    this->m_req_mutex.lock();
    normal_request* req = (normal_request*) this->m_request.data();

    requestInfo(req)->type = IMAGE_REQUEST;
    setRequestField(req, IMAGE_TIMESTAMP, timestamp);
    setRequestField(req, IMAGE_SEQ, seq);
    setRequestField(req, IMAGE_WIDTH, width);
    setRequestField(req, IMAGE_HEIGHT, height);
    setRequestField(req, IMAGE_TRAN_COUNT, once_count);

    sendRequest();
    this->m_req_mutex.unlock();
}

void ClientTransfer::trackRequest(int timestamp, int x1, int y1, int x2, int y2){
    this->m_req_mutex.lock();
    normal_request* req = (normal_request*) this->m_request.data();
    requestInfo(req)->type = TRACK_REQUEST;
    setRequestField(req, TRACK_TIMESTAMP, timestamp);
    setRequestField(req, TRACK_PT_X1, x1);
    setRequestField(req, TRACK_PT_X2, x2);
    setRequestField(req, TRACK_PT_Y1, y1);
    setRequestField(req, TRACK_PT_Y2, y2);

    sendRequest();

    this->m_req_mutex.unlock();
}

void ClientTransfer::ptzRequest(int x, int y, int z){
    this->m_req_mutex.lock();
    normal_request* req = (normal_request*) this->m_request.data();
    requestInfo(req)->type = PTZ_REQUEST;
    setRequestField(req, PTZ_X, x);
    setRequestField(req, PTZ_Y, y);
    setRequestField(req, PTZ_Z, z);

    sendRequest();

    this->m_req_mutex.unlock();
}

void ClientTransfer::setServer(QHostAddress addr, quint16 port){
    this->m_server_addr = addr;
    this->m_server_port = port;
//    this->m_timer.setInterval(10);
//    this->m_timer.start();
}
